package com.sskj.jgxt.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sskj.core.annotation.ControllerLogExeTime;
import com.sskj.core.exception.MException;
import com.sskj.jgxt.eng.domain.entity.DingJianDuEng;
import com.sskj.jgxt.jd.entity.FoundWT;
import com.sskj.jgxt.jd.entity.JianDuJiLuCJJG;
import com.sskj.jgxt.jd.entity.JianDuJiLuRenYuan;
import com.sskj.jgxt.jd.entity.ShiGongRiZhi;
import com.sskj.jgxt.jd.entity.WenTiFILE;
import com.sskj.jgxt.jd.entity.WenTiIMG;
import com.sskj.jgxt.jd.entity.WenTiLX;
import com.sskj.jgxt.jd.vo.ResultMegVO;
import com.sskj.jgxt.jd.vo.ShiGongRiZhiVO;
import com.sskj.jgxt.param.RiZhiQueryParam;
import com.sskj.jgxt.repository.JianDuEngRepository;
import com.sskj.jgxt.repository.ShiGongRiZhiRepository;
import com.sskj.jgxt.trans.ShiGongRiZhiTrans;
import com.sskj.personnel.domain.entity.EmployeeEntity;
import com.sskj.personnel.repository.EmployeeRepository;
import com.sskj.utils.CalendarUtil;
import com.sskj.utils.CodingUtil;
import com.sskj.utils.HttpUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping(value = "/wechat/sgrzjl", method = { RequestMethod.POST, RequestMethod.GET })
@Transactional
@Api(value = "施工日志记录", description = "施工日志记录")
public class WeChartRiZhiShiGongServiceImpl {

	protected final Log logger = LogFactory.getLog(WeChartRiZhiShiGongServiceImpl.class);

	@Autowired
	ShiGongRiZhiRepository repository;

	@Autowired
	JianDuEngRepository engrepository;	
	
	@Autowired
	EmployeeRepository employeeRepository;

	@Value("${sskj.conf.restUrl}")
	private String restUrl;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/page")
	@ControllerLogExeTime(description = "查询施工日志信息", log = false)
	@ApiOperation(value = "查询施工日志信息", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userid", value = "用户", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "keyword", value = "关键字", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "engid", value = "工程", paramType = "form", dataType = "string"),			
			@ApiImplicitParam(name = "rq", value = "日期", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<ShiGongRiZhi> queryPage(@ApiIgnore RiZhiQueryParam queryParam, @ApiIgnore Pageable pageable) {

			try {
				if (StringUtils.isEmpty(queryParam.getEngid()))
				{
					queryParam.setEngid("xxxxxxxx");
				}				
				if (StringUtils.isNotEmpty( queryParam.getRq()))
				{

					SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
					Date date =sdf.parse(queryParam.getRq());
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date);		
					queryParam.setXcrq(calendar);			
					
					Page<ShiGongRiZhi> page = repository.findXCRQJLPage(queryParam, pageable);				
					
					return page;
					
				}
				else
				{
					
					Page<ShiGongRiZhi> page = repository.findNameJLPage(queryParam, pageable);				
					
					return page;					
										
				}
				
			} catch (ParseException e) {
				return null;
				
			}
		
	}
	
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/control")
	@ControllerLogExeTime(description = "查询施工日志信息", log = false)
	@ApiOperation(value = "查询施工日志信息", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userid", value = "用户", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "keyword", value = "关键字", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "engid", value = "工程", paramType = "form", dataType = "string"),			
			@ApiImplicitParam(name = "rq", value = "日期", paramType = "form", dataType = "string"),
			@ApiImplicitParam(name = "pageNumber", value = "页号", paramType = "form", dataType = "int"),
			@ApiImplicitParam(name = "pageSize", value = "页的大小", paramType = "form", dataType = "int") })
	public Page<ShiGongRiZhi> queryControl(@ApiIgnore RiZhiQueryParam queryParam, @ApiIgnore Pageable pageable) {

			try {
				
				if (StringUtils.isNotEmpty( queryParam.getRq()))
				{

					SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
					Date date =sdf.parse(queryParam.getRq());
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date);		
					queryParam.setXcrq(calendar);			
					
					Page<ShiGongRiZhi> page = repository.findXCRQJLPage(queryParam, pageable);				
					
					return page;
					
				}
				else
				{
					
					Page<ShiGongRiZhi> page = repository.findNameJLPage(queryParam, pageable);				
					
					return page;					
										
				}
				
			} catch (ParseException e) {
				return null;
				
			}
		
	}	

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ApiOperation(value = "新增施工日志记录", notes = "新增施工日志记录", httpMethod = "POST")
	public ResultMegVO save(@RequestBody ShiGongRiZhi jl) throws Exception {
		ResultMegVO result = new ResultMegVO();
		ShiGongRiZhi oldJiLu = null;

		if (jl.getId() != null) {
			oldJiLu = repository.get(jl.getId());
		}

		if (oldJiLu == null) {
			String cdlike = "SGRZ-" + CalendarUtil.getYearyyyy(Calendar.getInstance()) + "-%";
			Integer cdlen = 14;
			String maxCode = repository.maxCode(cdlike, cdlen);
			String coding = CodingUtil.getMaxIDQuery(maxCode, cdlike, cdlen);
			jl.setCoding(coding);
			List<DingJianDuEng> engls = engrepository.findLsByOId(jl.getEng().getId());
			if(engls.isEmpty())
			{				
				jl.getEng().setOid(jl.getEng().getId());
				jl.getEng().setId(null);
			}
			else
			{
				jl.setEng(engls.get(0));
			}


		}

		for (JianDuJiLuRenYuan jdry : jl.getJdrys()) {
			EmployeeEntity emp = employeeRepository.findByDD_Id(jdry.getEmplId());
			if (emp != null) {
				jdry.setUserId(emp.getResteasy_emp_id());
			}
			jdry.setJdjl(jl);
			jdry.setCreatorId(jl.getCreatorId());

		}

		for (JianDuJiLuCJJG cjjg : jl.getCjjgs()) {
			cjjg.setJdjl(jl);
			cjjg.setCreatorId(jl.getCreatorId());

		}

		for (WenTiIMG img : jl.getImages()) {
			img.setJdjl(jl);
			img.setCreatorId(jl.getCreatorId());
		}

		for (FoundWT wt : jl.getWt()) {
			wt.setJdjl(jl);
			for (WenTiFILE file : wt.getFiles()) {
				file.setWt(wt);
				file.setCreatorId(jl.getCreatorId());
			}

			for (WenTiIMG img : wt.getImages()) {
				img.setWt(wt);
				img.setCreatorId(jl.getCreatorId());
			}

			for (WenTiLX lx : wt.getWtlx()) {
				lx.setWt(wt);
				lx.setCreatorId(jl.getCreatorId());
			}
		}

		try {
			repository.save(jl);
			result.setCode(jl.getId());
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("失败");
			e.printStackTrace();
			throw new MException("request_timeout");
		}				
		logger.info("输出"+result.getCode());
		return result;	

	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/upload", method = { RequestMethod.POST })
	@ApiOperation(value = "上传施工日志记录", notes = "上传施工日志记录", httpMethod = "POST")	
	public void upload(@RequestBody RiZhiQueryParam queryParam) throws Exception {

		try {
			String id = queryParam.getId();
			ShiGongRiZhi oldJiLu = repository.get(id);
			oldJiLu.setIsUpload(true);
			uploadJd(oldJiLu);
			repository.save(oldJiLu);
			logger.info("施工上传"+oldJiLu.getCoding()+restUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 同步往监督系统
	public void uploadJd(ShiGongRiZhi jl)  {

		ShiGongRiZhiTrans trans = new ShiGongRiZhiTrans(jl);
		ShiGongRiZhiVO vo = trans.returnVO();
		EmployeeEntity emp = employeeRepository.findByDD_Id(jl.getCreatorId());
		if (emp != null) {
			vo.setCreateId(emp.getResteasy_emp_id());
		}
		JSONObject obj = HttpUtils.httpPost(restUrl + "dingtalk/jd/sgrizhi/up", vo);
		if (null == obj) {
			
		}

	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/get", method = { RequestMethod.POST })
	@ApiImplicitParams({ @ApiImplicitParam(name = "spId", value = "记录ID", paramType = "form", dataType = "string") })
	@ApiOperation(value = "获取施工日志记录", notes = "获取施工日志记录", httpMethod = "GET")
	public ShiGongRiZhi get(String spId) throws Exception {

		ShiGongRiZhi jl = repository.findOneById(spId);
		return jl;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/del", method = { RequestMethod.POST, RequestMethod.DELETE })
	@ApiOperation(value = "删除施工日志记录", notes = "删除施工日志记录  多个施工日志记录ID用,号分隔", httpMethod = "DELETE")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "施工日志记录 IDS", paramType = "form", required = true, dataType = "string") })
	public void del(String id) {
		if (StringUtils.isNotEmpty(id)) {
			String[] idsArr = id.split(",");
			List<String> list = new ArrayList<String>();

			if (idsArr != null) {
				for (String idd : idsArr) {
					if (!idd.equals("ADMIN")) {
						list.add(idd);
					}
				}
				repository.delete(list);
			}
		}
	}

}
